package dca.sistemascontrole.view;

import dca.sistemascontrole.view.configuracao.PanelMalhaFechada;
import dca.sistemascontrole.view.configuracao.PanelMalhaAberta;
import dca.sistemascontrole.view.grafico.OfflineChartsDialog;
import dca.sistemascontrole.dao.GraphicDataManager;
import dca.sistemascontrole.exception.LogManager;
import dca.sistemascontrole.handler.HandlerMainFrame;
import dca.sistemascontrole.util.ControleConstantes;
import dca.sistemascontrole.util.XMLManager;
import dca.sistemascontrole.view.configuracao.PanelSeguidorReferencia;
import dca.sistemascontrole.view.configuracao.PanelVariaveisEstado;
import dca.sistemascontrole.view.estimacaoestado.FrameEstadoEstimado;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import org.jfree.data.time.FixedMillisecond;

/**
 *
 * @author Rafael
 */
public class MainFrame extends javax.swing.JFrame {

    private String openPath;
    private DialogTanques dialogTanques;
    private HandlerMainFrame handlerMainFrame;
    private PanelMalhaAberta pnlMalhaAberta;
    private PanelMalhaFechada pnlMalhaFechada;
    private PanelOpcoesGrafico pnlOpcoesGrafico;
    private PanelVariaveisEstado pnlVariaveisEstado;
    private PanelSeguidorReferencia pnlSeguidorReferencia;

    public MainFrame() {
        initComponents();
        handlerMainFrame = new HandlerMainFrame(this, pnlAnalises);

        pnlOpcoesGrafico = new PanelOpcoesGrafico(graficoNivel, graficoTensao, handlerMainFrame);
        pnlOpcoesGraficoHolder.add(pnlOpcoesGrafico);

        pnlMalhaAberta = new PanelMalhaAberta(handlerMainFrame);
        pnlMalhaAbertaHolder.add(pnlMalhaAberta);

        pnlMalhaFechada = new PanelMalhaFechada(handlerMainFrame);
        pnlMalhaFechadaHolder.add(pnlMalhaFechada);
        
        pnlVariaveisEstado = new PanelVariaveisEstado(handlerMainFrame);
        pnlVariaveisEstadoHolder.add(pnlVariaveisEstado);
        
        pnlSeguidorReferencia = new PanelSeguidorReferencia(handlerMainFrame);
        pnlSeguidorReferenciaHolder.add(pnlSeguidorReferencia);

        dialogTanques = new DialogTanques(this, false);

        graficoNivel.setXyplotTensao(graficoTensao.getXyplot());
        graficoTensao.setXyplotNivel(graficoNivel.getXyplot());

        handlerMainFrame.iniciarClock();
    }

    public void setVariaveisTensao(double uSaturado, double u, double ui, double up, double ud, long t) {
        graficoTensao.addValue(uSaturado, u, ui, up, ud, new FixedMillisecond(t));
    }

    public void setVariaveisNivel(double valueSuperior, double valueInferior, double setPoint, double erro, long t, double referencia) {
        dialogTanques.setNivelTanqueSuperior(valueSuperior);
        dialogTanques.setNivelTanqueInferior(valueInferior);
        
        graficoNivel.addValue(referencia, valueSuperior, valueInferior, setPoint, erro, new FixedMillisecond(t));
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        graficoNivel = new dca.sistemascontrole.view.grafico.GraficoNivel();
        graficoTensao = new dca.sistemascontrole.view.grafico.GraficoTensao();
        jPanel4 = new javax.swing.JPanel();
        btnInterromper = new dca.sistemascontrole.view.components.CustomButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        pnlMalhaAbertaHolder = new javax.swing.JPanel();
        pnlMalhaFechadaHolder = new javax.swing.JPanel();
        pnlOpcoesGraficoHolder = new javax.swing.JPanel();
        pnlAnalisesHolder = new javax.swing.JPanel();
        pnlAnalises = new dca.sistemascontrole.view.PanelAnalises();
        pnlVariaveisEstadoHolder = new javax.swing.JPanel();
        pnlSeguidorReferenciaHolder = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        menuSalvar = new javax.swing.JMenuItem();
        menuCarregar = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        menuConfigurarPortas = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        menuExibirTanques = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new java.awt.BorderLayout());

        jSplitPane1.setBorder(null);
        jSplitPane1.setDividerLocation(800);
        jSplitPane1.setDividerSize(2);
        jSplitPane1.setResizeWeight(1.0);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        graficoNivel.setBackground(new java.awt.Color(255, 255, 255));
        graficoNivel.setBorder(javax.swing.BorderFactory.createTitledBorder("Variáveis de Nível"));

        graficoTensao.setBackground(new java.awt.Color(255, 255, 255));
        graficoTensao.setBorder(javax.swing.BorderFactory.createTitledBorder("Variáveis de Tensão"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(graficoNivel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(graficoTensao, javax.swing.GroupLayout.DEFAULT_SIZE, 788, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(graficoNivel, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(graficoTensao, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));

        btnInterromper.setBackground(new java.awt.Color(250, 250, 250));
        btnInterromper.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dca/sistemascontrole/view/resources/icon_parar.png"))); // NOI18N
        btnInterromper.setText("Interromper");
        btnInterromper.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInterromperActionPerformed(evt);
            }
        });

        pnlMalhaAbertaHolder.setBackground(new java.awt.Color(255, 255, 255));
        pnlMalhaAbertaHolder.setLayout(new java.awt.BorderLayout());
        jTabbedPane1.addTab("Ativar Malha Aberta", pnlMalhaAbertaHolder);

        pnlMalhaFechadaHolder.setBackground(new java.awt.Color(255, 255, 255));
        pnlMalhaFechadaHolder.setLayout(new java.awt.BorderLayout());
        jTabbedPane1.addTab("Ativar Malha Fechada", pnlMalhaFechadaHolder);

        pnlOpcoesGraficoHolder.setBackground(new java.awt.Color(255, 255, 255));
        pnlOpcoesGraficoHolder.setLayout(new java.awt.BorderLayout());
        jTabbedPane1.addTab("Opções do Gráfico", pnlOpcoesGraficoHolder);

        pnlAnalisesHolder.setLayout(new java.awt.BorderLayout());
        pnlAnalisesHolder.add(pnlAnalises, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("Analises", pnlAnalisesHolder);

        pnlVariaveisEstadoHolder.setBackground(new java.awt.Color(255, 255, 255));
        pnlVariaveisEstadoHolder.setLayout(new java.awt.BorderLayout());
        jTabbedPane1.addTab("Variaveis de Estado", pnlVariaveisEstadoHolder);

        pnlSeguidorReferenciaHolder.setBackground(new java.awt.Color(255, 255, 255));
        pnlSeguidorReferenciaHolder.setLayout(new java.awt.BorderLayout());
        jTabbedPane1.addTab("Seguidor de Referencia", pnlSeguidorReferenciaHolder);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1)
                    .addComponent(btnInterromper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnInterromper, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jSplitPane1.setRightComponent(jPanel4);

        jPanel2.add(jSplitPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        jMenu1.setText("Arquivo");

        menuSalvar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        menuSalvar.setText("Salvar");
        menuSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuSalvarActionPerformed(evt);
            }
        });
        jMenu1.add(menuSalvar);

        menuCarregar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        menuCarregar.setText("Carregar");
        menuCarregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCarregarActionPerformed(evt);
            }
        });
        jMenu1.add(menuCarregar);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Configurações");

        menuConfigurarPortas.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK));
        menuConfigurarPortas.setText("Configurar Portas");
        menuConfigurarPortas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuConfigurarPortasActionPerformed(evt);
            }
        });
        jMenu2.add(menuConfigurarPortas);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Exibir");

        menuExibirTanques.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.ALT_MASK));
        menuExibirTanques.setText("Exibir Tanques");
        menuExibirTanques.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuExibirTanquesActionPerformed(evt);
            }
        });
        jMenu3.add(menuExibirTanques);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Exibir Estimação");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem1);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnInterromperActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInterromperActionPerformed
        handlerMainFrame.interromper();
    }//GEN-LAST:event_btnInterromperActionPerformed

    private void menuSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSalvarActionPerformed
        try {
            handlerMainFrame.saveGraphicData();
        } catch (FileNotFoundException ex) {
            LogManager.logErro(ex, "Não foi possível salvar o arquivo com os dados do gráfico.");
            JOptionPane.showMessageDialog(this, "Não foi possíve. salvar o arquivo com os dados do gráfico.");
        } catch (IOException ex) {
            LogManager.logErro(ex, "Não foi possível salvar o arquivo com os dados do gráfico.");
            JOptionPane.showMessageDialog(this, "Não foi possível salvar o arquivo com os dados do gráfico.");
        }
    }//GEN-LAST:event_menuSalvarActionPerformed

    private void menuCarregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCarregarActionPerformed
        JFileChooser fileChooser = new JFileChooser(openPath);
        fileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                String[] split = f.getName().split("\\.");
                return split[split.length - 1].equals(ControleConstantes.FILE_IDENTIFICADOR_DADOS) || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "Filtro boladao";
            }
        });

        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int option = fileChooser.showOpenDialog(this);

        if (option == JFileChooser.APPROVE_OPTION) {
            String absolutePath = fileChooser.getSelectedFile().getAbsolutePath();
            openPath = fileChooser.getSelectedFile().getParent();
            
            try {
                GraphicDataManager dataManager = XMLManager.readObject(absolutePath);
                if (dataManager != null) {
                    OfflineChartsDialog offlineChartsDialog = new OfflineChartsDialog(dataManager, this, false);
                    offlineChartsDialog.setVisible(true);
                }
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(this, "Não foi possível carregar dados salvos dos sinais.");
                LogManager.logErro(ex, "Não foi possível carregar dados salvos dos sinais.");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Não foi possível carregar dados salvos dos sinais.");
                LogManager.logErro(ex, "Não foi possível carregar dados salvos dos sinais.");
            }
        }
    }//GEN-LAST:event_menuCarregarActionPerformed

    private void menuConfigurarPortasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuConfigurarPortasActionPerformed
        handlerMainFrame.showDialogoConfiguração();
    }//GEN-LAST:event_menuConfigurarPortasActionPerformed

    private void menuExibirTanquesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuExibirTanquesActionPerformed
        dialogTanques.setVisible(true);
    }//GEN-LAST:event_menuExibirTanquesActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        FrameEstadoEstimado.getINSTANCE().setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    public static void main(String[] args) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dca.sistemascontrole.view.components.CustomButton btnInterromper;
    private dca.sistemascontrole.view.grafico.GraficoNivel graficoNivel;
    private dca.sistemascontrole.view.grafico.GraficoTensao graficoTensao;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JMenuItem menuCarregar;
    private javax.swing.JMenuItem menuConfigurarPortas;
    private javax.swing.JMenuItem menuExibirTanques;
    private javax.swing.JMenuItem menuSalvar;
    private dca.sistemascontrole.view.PanelAnalises pnlAnalises;
    private javax.swing.JPanel pnlAnalisesHolder;
    private javax.swing.JPanel pnlMalhaAbertaHolder;
    private javax.swing.JPanel pnlMalhaFechadaHolder;
    private javax.swing.JPanel pnlOpcoesGraficoHolder;
    private javax.swing.JPanel pnlSeguidorReferenciaHolder;
    private javax.swing.JPanel pnlVariaveisEstadoHolder;
    // End of variables declaration//GEN-END:variables
}
